package it.enrico.mangamania.inventario.server;

import it.enrico.mangamania.inventario.client.Fumetto;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class CaricamentoServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {


		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		List<Fumetto> fumetti = new ArrayList<Fumetto>();
		
		ServletFileUpload upload = new ServletFileUpload();
		try{
	            FileItemIterator iter = upload.getItemIterator(req);

	            while (iter.hasNext()) {
	                FileItemStream item = iter.next();

	                String name = item.getFieldName();
	                InputStream stream = item.openStream();

	               String ciao = convertStreamToString(stream);
	               StringTokenizer tk = new StringTokenizer(ciao, "\n");
	               while (tk.hasMoreTokens())
	               {
	            	   String fumettoStringa = tk.nextToken();
	            	   StringTokenizer st = new StringTokenizer(fumettoStringa,";");
	            	   while (st.hasMoreTokens())
	            	   {
	            		   Fumetto fumetto = new Fumetto();
	            		   String titolo = st.nextToken();
	            		   String prezzo = st.nextToken();
	            		   String casaEditrice = st.nextToken();
	            		   String categoria = st.nextToken();
	            		   String codice = st.nextToken();
	            		   
	            		   fumetto.setCategoria(categoria);
	            		   fumetto.setCodice(codice);
	            		   fumetto.setDescrizione(titolo);
	            		   fumetto.setEdizioni(casaEditrice);
	            		   fumetto.setNome(titolo);
	            		   fumetto.setPrezzo(new Double(prezzo.trim().replace(",", ".")));
	            		   fumetto.setQuantitaAcquistata(0L);
	            		   fumetto.setQuantitaVenduta(0L);
	            		   fumetto.setDataInserimento(new Date());
	            		   fumetto.setDataUltimaModifica(new Date());
	            		   
	            		   System.out.println("Ineserisco Fumetto: "+fumettoStringa);
	            		  pm.makePersistent(fumetto);
	            		  pm.flush();
	            	   
	            	   }
	            	   
	               }
	               
	               
	               
	                
	            }
	        }
		
			
		
	        catch(Exception e){
	        	resp.getWriter().print(e.getMessage());
	        }
	        
	      
	
	}
	
	
	
	public String convertStreamToString(InputStream is) throws IOException {
		        /*
		         * To convert the InputStream to String we use the BufferedReader.readLine()
		         * method. We iterate until the BufferedReader return null which means
		         * there's no more data to read. Each line will appended to a StringBuilder
		         * and returned as String.
		         */
		        if (is != null) {
		            StringBuilder sb = new StringBuilder();
		            String line;
		 
		            try {
		                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		                while ((line = reader.readLine()) != null) {
		                    sb.append(line).append("\n");
	                }
		            } finally {
		                is.close();
		            }
		            return sb.toString();
		        } else {       
		            return "";
		        }
	}
}